package edu.nus.mtech.sem1.ca.main;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.swing.ButtonGroup;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.TitledBorder;

import edu.nus.mtech.sem1.ca.auth.UserRole;
import edu.nus.mtech.sem1.ca.cust.Customer;
import edu.nus.mtech.sem1.ca.exception.CustomerNotFoundException;
import edu.nus.mtech.sem1.ca.main.dao.TelephonyApplicationDao;
import edu.nus.mtech.sem1.ca.utils.Common;
import edu.nus.mtech.sem1.ca.utils.DateInputControl;
import edu.nus.mtech.sem1.ca.utils.Logger;
import edu.nus.mtech.sem1.ca.utils.TelephonyUtils;



public class FormBillGenerator extends JInternalFrame {
	private JTextField txtName;
	private JTextField txtAcctNo;
	private JTextField txtEmail;
	private JTextField txtNRIC;
	private JTextField txtFromDate;
	private JTextField txtToDate;
	private UserRole mRole = UserRole.AGENT;
	private JComboBox cboMonth;
	private TelephonyApplicationDao dao=null;
	private List<java.util.Date> mAvailableMonths=new ArrayList<java.util.Date>();
	private ComboBoxModel mComboboxModel;
	
	
	private Customer customer=null;

	/**
	 * Create the frame.
	 */
	public FormBillGenerator(UserRole aRole) {
		mRole = aRole;
		Initialize();		
	}

	public FormBillGenerator() {
		mRole=Common.USER_ROLE;
		Initialize();
		LoadAvailableMonths();
	}
	
	public FormBillGenerator(Customer customer) {
		mRole=Common.USER_ROLE;
		Initialize();
		LoadAvailableMonths();
		bindControls(customer);
	}
	

	private void Initialize() {
	
		
		dao=new TelephonyApplicationDao();
		
		setClosable(true);
		setTitle("Generate Bill");
		setBounds(100, 100, 479, 330);
		getContentPane().setLayout(null);

		JButton btnGenerateBill = new JButton("Generate Bill");
		btnGenerateBill.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				try {
					GenerateEach(customer);
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} 
				catch(CustomerNotFoundException cusex){
					JOptionPane.showMessageDialog(null, cusex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		});
		btnGenerateBill.setBounds(119, 242, 180, 23);
		getContentPane().add(btnGenerateBill);

		JButton btnGenerateAll = new JButton("Generate All Customers");
		btnGenerateAll.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				try {
					GenerateAll();
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		btnGenerateAll.setBounds(119, 217, 180, 23);
		getContentPane().add(btnGenerateAll);
		if (mRole != UserRole.ADMIN)
			btnGenerateAll.setVisible(false);

		JPanel panelCustomer = new JPanel();
		panelCustomer.setBorder(new TitledBorder(null, "Customer Info",
				TitledBorder.LEADING, TitledBorder.TOP, null, null));
		panelCustomer.setBounds(10, 11, 443, 164);
		getContentPane().add(panelCustomer);
		panelCustomer.setLayout(null);

		JLabel label_2 = new JLabel("Account No.");
		label_2.setBounds(23, 65, 75, 14);
		panelCustomer.add(label_2);
		label_2.setHorizontalAlignment(SwingConstants.LEFT);

		JLabel label_1 = new JLabel("NRIC");
		label_1.setBounds(23, 36, 75, 14);
		panelCustomer.add(label_1);

		JLabel label = new JLabel("Name");
		label.setBounds(23, 96, 75, 14);
		panelCustomer.add(label);

		JLabel label_3 = new JLabel("Email");
		label_3.setBounds(23, 127, 46, 14);
		panelCustomer.add(label_3);
		label_3.setHorizontalAlignment(SwingConstants.LEFT);

		txtEmail = new JTextField();
		txtEmail.setBounds(108, 124, 180, 20);
		panelCustomer.add(txtEmail);
		txtEmail.setColumns(10);

		txtName = new JTextField();
		txtName.setBounds(108, 93, 180, 20);
		panelCustomer.add(txtName);
		txtName.setColumns(10);

		txtNRIC = new JTextField();
		txtNRIC.setBounds(108, 33, 180, 20);
		panelCustomer.add(txtNRIC);
		txtNRIC.setColumns(10);

		txtAcctNo = new JTextField();
		txtAcctNo.setBounds(108, 62, 180, 20);
		panelCustomer.add(txtAcctNo);

		JButton btnSearch = new JButton("Search by NRIC");
		btnSearch.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					customer=SearchCustomer();
				} catch (CustomerNotFoundException exp) {
					// TODO: handle exception
					JOptionPane.showMessageDialog(null, exp.getMessage(), "Info", JOptionPane.INFORMATION_MESSAGE);
					Logger.log(exp.getMessage());
				}
			}
		});
		btnSearch.setBounds(296, 30, 138, 23);
		panelCustomer.add(btnSearch);

		txtFromDate = new DateInputControl();
		txtFromDate.setColumns(10);

		txtToDate = new DateInputControl();
		txtToDate.setColumns(10);
		
				cboMonth = new JComboBox();
				cboMonth.setBounds(119, 186, 180, 20);
				getContentPane().add(cboMonth);
				//cboMonth.addItem("01");
				//cboMonth.addItem("02");
				
				JLabel lblGenerateFor = new JLabel("Generate For");
				lblGenerateFor.setBounds(30, 189, 88, 14);
				getContentPane().add(lblGenerateFor);

		ButtonGroup l_group = new ButtonGroup();
	}

	private void LoadAvailableMonths(){
		
		java.util.Date l_startDate=new java.util.Date();
		java.util.Date l_endDate=new java.util.Date();
		
		String[] monthNames = {"January", "February",
				"March", "April", "May", "June", "July",
				"August", "September", "October", "November",
				"December"};
		
		Calendar l_calendar= Calendar.getInstance();
		l_calendar.add(Calendar.MONTH, -6);
		
		l_startDate=l_calendar.getTime();	
		
		List<String> l_months = new ArrayList<String>();
		
		while(l_startDate.before(l_endDate)){
			String l_key = monthNames[l_startDate.getMonth()]+" "+l_calendar.get(Calendar.YEAR);
			mAvailableMonths.add(l_startDate);
			l_months.add(l_key);
			l_calendar.setTime(l_startDate);
			l_calendar.add(Calendar.MONTH, 1);
			l_startDate=l_calendar.getTime();
		}
		
		mComboboxModel = new DefaultComboBoxModel(l_months.toArray());
		cboMonth.setModel(mComboboxModel);		
	}
	private Customer SearchCustomer() throws CustomerNotFoundException {
		//Customer mCustomer =null;
		try {
			customer = new Customer();
			customer = dao.retrieveCustomerData(txtNRIC.getText().trim());
			bindControls(customer);
		} catch (CustomerNotFoundException e) {
			// TODO: handle exception
			throw e;
		}
		return customer;
	}

	private void bindControls(Customer mCustomer) {
		txtName.setText(mCustomer.getName());
		txtEmail.setText(mCustomer.getEmail());
		txtNRIC.setText(mCustomer.getNric());
		txtAcctNo.setText(mCustomer.getAccountNo());
	}

	private void GenerateEach(Customer mCustomer) throws IllegalArgumentException, Exception {
		TelephoneApplication l_generator = new TelephoneApplication();
		try {
			SearchCustomer();
		} catch (CustomerNotFoundException e) {
			// TODO: handle exception
			JOptionPane.showMessageDialog(null, e.getMessage(), "Info", JOptionPane.INFORMATION_MESSAGE);
			Logger.log(e.getMessage());
		}
		java.util.Date startDate= mAvailableMonths.get(cboMonth.getSelectedIndex());	
		Calendar l_cal=Calendar.getInstance();
		 l_cal.setTime(startDate);
		 String l_string = "01/"+ Integer.toString(l_cal.get(Calendar.MONTH)+1) +"/"+ Integer.toString(l_cal.get(Calendar.YEAR));
		 startDate = TelephonyUtils.getDateFromString(l_string);

		 l_cal.setTime(startDate);
		 l_cal.add(Calendar.MONTH, 1);
		
		 java.util.Date endDate= l_cal.getTime();

		l_generator.generateBill(customer, customer.getNric(), startDate,
				endDate);		

	}

	private void GenerateAll() throws IllegalArgumentException, Exception {
		TelephoneApplication l_generator = new TelephoneApplication();
		java.util.Date startDate= mAvailableMonths.get(cboMonth.getSelectedIndex());	
		Calendar l_cal=Calendar.getInstance();
		 l_cal.setTime(startDate);
		 String l_string = "01/"+ Integer.toString(l_cal.get(Calendar.MONTH)+1) +"/"+ Integer.toString(l_cal.get(Calendar.YEAR));
		 startDate = TelephonyUtils.getDateFromString(l_string);

		 l_cal.setTime(startDate);
		 l_cal.add(Calendar.MONTH, 1);
		
		 java.util.Date endDate= l_cal.getTime();

		Logger.log("start date" + startDate + "End Date : " + endDate);
		l_generator.generateBillAll(startDate, endDate);
		
	}
}
